package com.deng.mail.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.Arrays;

@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    @ResponseBody
    @GetMapping(value = "/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping(value = "/boss")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            // 去ssoserver登陆成功跳回来会带上
            // todo 去ssoserver获取当前token真正对应的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://localhost:8080/userinfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser", body);
        }
        if (session.getAttribute("loginUser") == null) {
            // 没登陆，跳转到登录服务器登录
            return "redirect:" + ssoServerUrl + "?redirect_url=http://localhost:8082/boss";
        } else {
            model.addAttribute("emps", Arrays.asList("张三", "里斯"));
            return "list";
        }

    }

}
